package com.example.service

import com.example.controller.request.UserRequest
import com.example.repository.UserProfileRepository
import com.example.repository.UserRepository
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

/**
 *
 *
 * @author wangli
 * @date 2025-10-10
 */
@Service
class UserService(
    private val userRepository: UserRepository,
    private val userProfileRepository: UserProfileRepository
) {

    @Transactional
    fun createUserWithTransaction(req: UserRequest): Long {
        val user = req.toUser()
        val userDO = user.createUser()
        userRepository.insert(userDO)
        val userId = userDO.id
        val userProfileDO = user.createUserProfile(userId!!)
        userProfileRepository.insert(userProfileDO)
        return userId
    }

    @Transactional
    fun createUserWithTransactionRollbackException(req: UserRequest): Long {
        val user = req.toUser()
        val userDO = user.createUser()
        userRepository.insert(userDO)
        val userId = userDO.id!!
        try {
            val userProfileDO = user.createUserProfile(userId)
            userProfileRepository.insertThrowException(userProfileDO)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return userId
    }

    @Transactional
    fun createUserWithTransactionAsync(req: UserRequest): Long {
        val user = req.toUser()
        val userDO = user.createUser()
        userRepository.insert(userDO)
        val userId = userDO.id!!
        val userProfileDO = user.createUserProfile(userId)
        userProfileRepository.insertThrowException(userProfileDO)
        return userId
    }
}